﻿using System;
using System.Data;
using System.IO;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class Basic_boar
    {
        public static BLL.Basic_boar product = new BLL.Basic_boar();
        public static Model.Basic_boar model = new Model.Basic_boar();
        static BLL.Sys_Param sp = new BLL.Sys_Param();
        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public Basic_boar()
        {
        }

        public Basic_boar(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {
            model.category_id = PageValidate.InputText(request["T_product_category_val"], 50);
            model.product_name = PageValidate.InputText(request["T_product_name"], 255);
            model.specifications = PageValidate.InputText(request["T_specifications"], 255);
            model.unit = PageValidate.InputText(request["T_product_unit"], 255);
            model.unit_id = PageValidate.InputText(request["T_product_unit_val"], 255);
            model.remarks = PageValidate.InputText(request["T_remarks"], 255);
            model.shortcode = PageValidate.InputText(request["T_shortcode"], 255);
            string txm = PageValidate.InputText(request["T_txm"], 255); 
            model.img_url = PageValidate.InputText(request["headurl"], 255);
            model.birthday = DateTime.Parse( PageValidate.InputText(request["T_bir"], 255));
            //
            model.sex = PageValidate.InputText(request["T_sex"],50);
            model.InDate = DateTime.Parse(request["T_InDate"]);
            model.sysId = PageValidate.InputText(request["T_sysId"],50);
            model.dormId = PageValidate.InputText(request["T_dormId_val"], 50);
            model.corralId = PageValidate.InputText(request["T_corralId_val"], 50);
            model.productId = PageValidate.InputText(request["T_productId_val"], 50);
            model.Pro_SeriesId = PageValidate.InputText(request["T_Pro_SeriesId_val"], 50);
            model.Pro_Series_LevelId = PageValidate.InputText(request["T_Pro_Series_LevelId_val"], 50);
            model.origin = PageValidate.InputText(request["T_origin"], 50);
            model.place = PageValidate.InputText(request["T_place"], 50);
           
            string pid = PageValidate.InputText(request["pid"], 50);
            string strwhere = "   barcode = '"+txm+"'";
            string s = $" shortcode= '{ model.shortcode}' ";
            if (PageValidate.checkID(pid))
            {
                s += $" AND ID!= '{ pid }' "; ;
            }
                DataSet ds1 = product.GetList(s);
            if (ds1.Tables[0].Rows.Count > 0)
                return XhdResult.Error("短号存在，更新失败！").ToString();
            if (PageValidate.checkID(pid))
            {

                strwhere += " AND ID='"+ pid + "'";
                //model.status = "Y";
                model.barcode = txm;
                model.id = pid;
                DataSet ds = product.GetList($" id= '{pid}' ");
                if (ds.Tables[0].Rows.Count == 0)
                    return XhdResult.Error("参数不正确，更新失败！").ToString();
                //DataSet dss = product.GetList(strwhere);
                //if (dss.Tables[0].Rows.Count > 0)
                //    return XhdResult.Error(txm+"标识码重复，更新失败！").ToString();


                DataRow dr = ds.Tables[0].Rows[0];
                product.Update(model);

                string UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.product_name;
                string EventType = "产品修改";
                string EventID = model.id;

                string Log_Content = null;

                //if (dr["category_name"].ToString() != request["T_product_category"])
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品类别", dr["category_name"],
                //        request["T_product_category"]);

                //if (dr["product_name"].ToString() != request["T_product_name"])
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品名字", dr["product_name"],
                //        request["T_product_name"]);

                //if (dr["specifications"].ToString() != request["T_specifications"])
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "产品规格", dr["specifications"],
                //        request["T_specifications"]);

                //if (dr["unit"].ToString() != request["T_product_unit"])
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "单位", dr["unit"], request["T_product_unit"]);

                //if (dr["remarks"].ToString() != request["T_Remark"])
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "备注", dr["remarks"], request["T_Remark"]);

                //if (decimal.Parse(dr["price"].ToString()) != decimal.Parse(request["T_price"]))
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "零售价", dr["price"], request["T_price"]);

                //if (decimal.Parse(dr["cost"].ToString()) != decimal.Parse(request["T_cost"]))
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "成本价", dr["cost"], request["T_cost"]);

                //if (decimal.Parse(dr["agio"].ToString()) != decimal.Parse(request["T_agio"]))
                //    Log_Content += string.Format("【{0}】{1} → {2} \n", "折扣价", dr["agio"], request["T_agio"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            { //增加默认状态
                model.CollectionStatus = 1;
                model.EfficacyState = 1;
                model.status = "Y";
                model.create_id = emp_id;
                model.create_time = DateTime.Now;
                model.id = Guid.NewGuid().ToString();
             
                if (txm == "")
                    model.barcode = sp.GetBarCode("BOAR");
                else model.barcode = txm;
                product.Add(model);
            }

            return XhdResult.Success().ToString();
        }



        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " create_time";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["categoryid"]))
                serchtxt += $" and category_id='{PageValidate.InputText(request["categoryid"], 50)}'";

            if (!string.IsNullOrEmpty(request["stext"]))
                serchtxt += $" and product_name+barcode+isnull(shortcode,'') like N'%{ PageValidate.InputText(request["stext"], 255) }%'";
            if (!string.IsNullOrEmpty(request["IsUse"]))
                if(request["IsUse"]=="Y")//当需求必须为可用状态似乎，采集状态和药效状态都必须生效  且不在在途
                serchtxt += " and CollectionStatus=1   AND EfficacyState=1 AND status='Y'";
            //状态选择
            if (!string.IsNullOrEmpty(request["T_sectype_val"]))
            {
                if (request["T_sectype_val"] == "0")//全部
                { }
                if (request["T_sectype_val"] == "1")//可采集
                { serchtxt += " and CollectionStatus=1"; }
                if (request["T_sectype_val"] == "2")//禁采期
                { serchtxt += " and CollectionStatus=3"; }
                        //serchtxt += " and  IsStatus='" + request["T_sectype_val"] + "'";
            }

            //权限
            DataSet ds = product.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }

        public string gridmx1()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " create_time";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["categoryid"]))
                serchtxt += $" and category_id='{PageValidate.InputText(request["categoryid"], 50)}'";

            if (!string.IsNullOrEmpty(request["stext"]))
                serchtxt += $" and product_name+barcode+shortcode like N'%{ PageValidate.InputText(request["stext"], 255) }%'";
            if (!string.IsNullOrEmpty(request["IsUse"]))
                if (request["IsUse"] == "Y")//当需求必须为可用状态似乎，采集状态和药效状态都必须生效  且不在在途
                    serchtxt += " and CollectionStatus=1   AND EfficacyState=1 AND status='Y'";
            //状态选择
            if (!string.IsNullOrEmpty(request["T_sectype_val"]))
            {
                if (request["T_sectype_val"] == "0")//全部
                { }
                if (request["T_sectype_val"] == "1")//可采集
                { serchtxt += " and CollectionStatus=1"; }
                if (request["T_sectype_val"] == "2")//禁采期
                { serchtxt += " and CollectionStatus=3"; }
                //serchtxt += " and  IsStatus='" + request["T_sectype_val"] + "'";
            }

            //权限
            DataSet ds = product.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = product.GetList($" id= '{id}' ");
            return DataToJson.DataToJSON(ds);

        }


        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return XhdResult.Error("参数错误！").ToString();
            id = PageValidate.InputText(id, 50);
            DataSet ds = product.GetList($" id= '{id}' ");
            if (ds.Tables[0].Rows.Count < 1)
                return XhdResult.Error("系统错误，无数据！").ToString();

            var ccod = new BLL.Sale_order_details();
            if (ccod.GetList($"product_id = '{id}'").Tables[0].Rows.Count > 0)
                return XhdResult.Error("此产品下含有订单，不允许删除！").ToString();

            

            bool candel = true;
            if (uid != "admin")
            {
                //controll auth
                var getauth = new GetAuthorityByUid();
                candel = getauth.GetBtnAuthority(emp_id.ToString(), "FDE2E0EE-D2B1-40BD-928F-AB28F58D770D");
                if (!candel)
                    return XhdResult.Error("无此权限！").ToString();
            }

            bool isdel = product.DeleteByid(id);
            if (!isdel) return XhdResult.Error("系统错误，删除失败！").ToString();

            //日志
            string EventType = "产品删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = ds.Tables[0].Rows[0]["product_name"].ToString();



            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }


        public string Base64Upload()
        {
            string base64txt = request["base64img"];
            string ext = "png";
            //处理文件头
            if (string.IsNullOrEmpty(base64txt))
                return null;

            int i = base64txt.IndexOf("image") + 6;
            int j = base64txt.IndexOf("base64");

            if (i > -1 && j - i - 1 > 0)
            {
                ext = base64txt.Substring(i, j - i - 1);
            }
            base64txt = base64txt.Substring(base64txt.IndexOf(',') + 1);

            Random rnd = new Random();
            string nowfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(10000, 99999) + "." + ext;

            string filetype = PageValidate.InputText(request["Type"], 50);

            string path = @"/Images/upload/Basicboar/" + nowfileName;



            //过滤特殊字符
            string dummyData = base64txt.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }

            StringToFile(dummyData, HttpContext.Current.Server.MapPath(path));

            return XhdResult.Success(nowfileName).ToString();
        }

        /// <summary>  
        /// 把经过base64编码的字符串保存为文件  
        /// </summary>  
        /// <param name="base64String">经base64加码后的字符串 </param>  
        /// <param name="fileName">保存文件的路径和文件名 </param>  
        /// <returns>保存文件是否成功 </returns>  
        private static bool StringToFile(string base64String, string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
            {
                bw.Write(Convert.FromBase64String(base64String));
            }
            bw.Close();
            fs.Close();
            return true;
        }


    }
}
